import { request, useUserStore, clearEmpty } from "jmash-core";
import type { AxiosPromise } from "axios";
import type {
  LogApi,
  LogReq,
  LogPage,
  LogKey,
  LogModel,
  LogExportReq,
} from "./types";
import qs from "qs";

class LogApiImpl implements LogApi {
  getKey(model: LogModel): LogKey {
    return {
      logId: model.logId,
    } as LogKey;
  }
  /**
   * 获取分页日志
   *
   * @param query 查询参数
   * @returns 返回请求结果
   */
  findPage(query: LogReq): AxiosPromise<LogPage> {
    query.tenant = useUserStore().user.tenant;
    clearEmpty(query);
    return request({
      url: "/v1/rbac/log/page",
      method: "get",
      params: query,
    });
  }

  // 查询操作日志
  findById(query: LogKey): AxiosPromise<LogModel> {
    query.tenant = useUserStore().user.tenant;
    clearEmpty(query);
    return request({
      url: "/v1/rbac/log/id",
      method: "get",
      params: query,
    });
  }
  /**
   * 批量删除日志
   *
   * @param year 年份
   * @returns 返回请求结果
   */
  batchDelLog(year: number): AxiosPromise<number> {
    const query = {
      tenant: useUserStore().user.tenant,
      number: year,
    };
    return request({
      url: "/v1/rbac/log/batch",
      method: "delete",
      params: query,
    });
  }

  /**
   * 导出日志到Excel文件
   *
   * @param queryParams 查询参数
   * @returns 返回一个Promise对象，用于处理异步操作
   */
  exportExcel(queryParams: LogExportReq): AxiosPromise {
    clearEmpty(queryParams);
    const query = qs.stringify(queryParams, {
      arrayFormat: "brackets",
      allowDots: true,
    });
    return request({
      url: "/v1/rbac/log/" + useUserStore().user.tenant + "/logs.xlsx?" + query,
      method: "get",
      responseType: "blob",
    });
  }
}

const logApi = new LogApiImpl();
export { logApi };
